package com.fortune.conf;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.fortune.entity.NewsEntity;
import com.fortune.mapper.NewsMapper;
import com.fortune.utils.AESUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: fortune
 * @description:
 * @author: wwb
 * @create: 2025-03-28 20:01
 */
// 自定义实现Pipeline接口
public class SavePipelineDate implements Pipeline {
private NewsMapper newsMapper;
private String typeCode;
public SavePipelineDate() {
}
public SavePipelineDate(String typeCode) {
    this.typeCode = typeCode;
}

        public void process(ResultItems resultitems, Task task) {
            Map<String, Object> mapResults = resultitems.getAll();
//        Iterator<Entry<String, Object>> iter = mapResults.entrySet().iterator();
//        Entry<String, Object> entry;
//        //输出到控制台
//        while (iter.hasNext()) {
//            entry = iter.next();
//            System.out.println(entry.getKey() + "：" + entry.getValue());
//        }
            // 持久化
//        News news = new News();

            NewsEntity newsEntity = new NewsEntity();
            if (mapResults.containsKey("title") && Objects.nonNull(mapResults.get("title"))) {
                newsEntity.setNewsTitle(removeHtmlTag(mapResults.get("title").toString().replace("<span class=\"original-logo\">原创</span>" , "")).trim());
            }
            if (mapResults.containsKey("content") && Objects.nonNull(mapResults.get("content"))) {
                String contentStr = mapResults.get("content").toString();
                contentStr = contentStr.startsWith("[") && contentStr.endsWith("]") ? contentStr.substring(1,contentStr.length()-1) : contentStr;

                if (mapResults.containsKey("contentImages") && Objects.nonNull(mapResults.get("contentImages"))) {
                    List<String> contentImages = (List)mapResults.get("contentImages");
                    for (int i = 0; i < contentImages.size(); i++) {
                        try {
                            String contentImage = contentImages.get(i);
                            String contentImageUrl = AESUtil.decrypt("www.sohu.com6666", contentImage);
                            String oneselfImage="";
                            if(StringUtils.isNotBlank(contentImageUrl)){
                                //加密数据 替换为已解密完成数据
                                contentStr = contentStr.replace(contentImage,contentImageUrl);

                                //https://images.xlcwx.com/xlcwx/m/community/2025/3/28/075ef604f39c4a40ad7ddbc0796204b5.jpeg
                                //转换本地自己的url,文件夹地址
                                String imageUrlPath = downImage(contentImageUrl);
                                //转换为自己的url，http地址
                                oneselfImage = "https://images.xlcwx.com/xlcwx/m/community/"+imageUrlPath;
                                contentStr = contentStr.replace(contentImageUrl,oneselfImage);
                            }
                            if(i==0){
                                newsEntity.setCoverUrl(oneselfImage);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }

                contentStr = contentStr.replace("<!-- 政务处理 --> ","").replace("<!-- 政务账号添加来源标示处理 -->","").
                        replace("<img max-width=\"600\"","<img ").
                        replace("<img",   "<img class=\"img-responsive\"").replace("data-src=\"http","src=\"http").
                        replace("<a href=\"//www.sohu.com/?strategyid=00001 \" target=\"_blank\" title=\"点击进入搜狐首页\" id=\"backsohucom\" style=\"white-space: nowrap;\"><span class=\"backword\"><i class=\"backsohu\"></i>返回搜狐，查看更多</span></a>","").
                        replace("返回搜狐，查看更多","");
                newsEntity.setNewsContent(contentStr);
            }

            if(StringUtils.isNotBlank(newsEntity.getNewsTitle()) && StringUtils.isNotBlank(newsEntity.getNewsContent())){
                newsMapper = SpringUtil.getApplicationContext().getBean(NewsMapper.class);;
                newsEntity.setCreateTime(new Date());
                newsEntity.setTypeCode(this.typeCode);
                newsMapper.insert(newsEntity);
            }
        }

    /**
     * 去除html标签
     * @param htmlStr
     * @return
     */
    public static String removeHtmlTag(String htmlStr) {
        //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
        String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
        //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
        String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
        //定义HTML标签的正则表达式
        String regEx_html = "<[^>]+>";
        //定义一些特殊字符的正则表达式 如：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        String regEx_special = "\\&[a-zA-Z]{1,10};";

        //1.过滤script标签
        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll("");
        //2.过滤style标签
        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll("");
        //3.过滤html标签
        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll("");
        //4.过滤特殊标签
        Pattern p_special = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
        Matcher m_special = p_special.matcher(htmlStr);
        htmlStr = m_special.replaceAll("");

        return htmlStr;
    }



    /**
     * 根据完整下载资源主要是图片到本地
     * @param urlStr 网址
     */
    public String downImage(String urlStr){
        String imageResultUrl="";
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前日期的年、月、日
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        int day = currentDate.getDayOfMonth();
        String dateDir = year+"/"+month+"/"+day+"/";

        String substring = urlStr.substring(0, 2);
        if("//".equals(substring)){
            substring = substring.replace("//","http://");
        }
        urlStr = substring+urlStr.substring(2,urlStr.length());
        String dir = "D:/wwb/1/fc_image/"+dateDir;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String[] images = urlStr.split("/");
        String imageNameAndExtend = images[images.length - 1];
        File file = new File(dir+imageNameAndExtend);//创建文件，dir=绝对路径+图片名称后缀
        try {
            File fileTemp = new File(dir);
            if(!fileTemp.exists()){
                fileTemp.mkdirs();
            }
            imageResultUrl = dateDir+imageNameAndExtend;

            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");// 声明请求方式
            urlConnection.setConnectTimeout(6 * 1000);// 设置连接超时
            urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip");
            inputStream = urlConnection.getInputStream();
            outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int n = 0;
            while((n = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,n);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        try {
            //gif 缩减大小
            GifCompressorFFmpeg.extremeCompress(dir+imageNameAndExtend,dir+imageNameAndExtend);
        }catch (Exception e){
            e.printStackTrace();
        }
        return imageResultUrl;
    }

    public static void main(String[] args) throws IOException {
//        compressSize();

        // 读取GIF的所有帧
        ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
        reader.setInput(ImageIO.createImageInputStream(new File("D:\\wwb\\1\\fc_image\\2025\\3\\29\\40f95a32169041c1adeb7d45e6f9cde5.gif")));
        int numFrames = reader.getNumImages(true);

// 逐帧压缩并保存
        BufferedImage[] frames = new BufferedImage[numFrames];
        for (int i = 0; i < numFrames; i++) {
            frames[i] = Thumbnails.of(reader.read(i))
                    .scale(1)
                    .outputQuality(0.7)
                    .asBufferedImage();
        }

// 生成新GIF（需配置帧延迟等参数）
        ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next();
        writer.setOutput(ImageIO.createImageOutputStream(new File("D:\\wwb\\1\\fc_image\\2025/40f95a32169041c1adeb7d45e6f9cde5.gif")));
        writer.prepareWriteSequence(null);
        for (BufferedImage frame : frames) {
            writer.writeToSequence(new IIOImage(frame, null, null), null);
        }
        writer.endWriteSequence();





    }
    public static void compressSize() throws FileNotFoundException {
        String filePath = "D:\\wwb\\1\\fc_image\\2025\\3\\29\\40f95a32169041c1adeb7d45e6f9cde5.gif"; // 文件路径
        File temp = new File(filePath);
//        InputStream im  = new FileInputStream(temp);
//        ClassPathResource resource = new ClassPathResource(filePath);

        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(temp);
            int i = 0;
            for (float quality = 0.9f; quality > 0.0f; quality -= 0.1f) {
                String path = StrUtil.format("D:\\wwb\\1\\fc_image\\2025/40f95a32169041c1adeb7d45e6f9cde5.gif", ++i);
                File distFile = new File(path);
                Thumbnails.of(inputStream)
                        .scale(quality)
                        .outputQuality(0.5) // 输出的图片质量
//                        .outputFormat("gif")
                        .toFile(distFile);
                long length = distFile.length();
                if (length / 1024 <= 5120) { // 压缩至5MB左右
                    System.out.println(length / (1024 * 1024) + "MB");
                    break;
                }
                if (ObjectUtil.isNull(inputStream) || inputStream.available() == 0) {
                    inputStream = new FileInputStream(distFile);
                }
                distFile.delete();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            IoUtil.close(inputStream);
        }

    }






}